
package com.platform.modules.mall.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.Producer;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.Constant;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.RestResponse;
import com.platform.config.KaptchaConfig;
import com.platform.modules.mall.entity.MallUserCardEntity;
import com.platform.modules.mall.service.MallUserCardService;
import com.platform.modules.sms.util.SmsUtil;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysSmsLogService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import cn.hutool.core.lang.Validator;
/**
 * 用户卡卷Controller
 *
 * @author
 * @date 2023-08-25 09:37:20
 */
@RestController
@RequestMapping("mall/usercard")
public class MallUserCardController extends AbstractController {
    @Autowired
    private MallUserCardService mallUserCardService;

    @Autowired
    private SysSmsLogService sysSmsLogService;

    @Autowired
    private JedisUtil jedisUtil;


    @Resource
    private Producer producer;

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("mall:usercard:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<MallUserCardEntity> list = mallUserCardService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询用户卡卷
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:usercard:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = mallUserCardService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:usercard:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallUserCardEntity mallUserCard = mallUserCardService.getById(id);
        mallUserCard.setCardSn("****");
        return RestResponse.success().put("usercard", mallUserCard);
    }

    /**
     * 验证码
     *
     * @param response response
     * @param uuid     uuid
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("uuid不能为空");
        }
        // 生成文字验证码
        String code = producer.createText();
        // 保存至redis有效期五分钟
        jedisUtil.set(KaptchaConfig.REDIS_KYE + uuid, code, KaptchaConfig.VALID_TIME);
        // 获取图片验证码
        BufferedImage image = producer.createImage(code);
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("sendSms")
    public RestResponse sendSms(@RequestBody Map<String, String> params) {
        SysUserEntity user = this.getUser();
        if(!Validator.isMobile(user.getMobile())){
            throw new BusinessException("您没有绑定手机号，请绑定手机！");
        }
        sysSmsLogService.build(user.getMobile())
                .captchaValidate(params.get("uuid"), params.get("code"))
                .autoSend(params.get("configId"), params);
        return RestResponse.success("短信发送成功");
    }

    @PostMapping("verificationCardSn")
    public RestResponse verificationCardSn(@RequestBody Map<String, String> params) {
        SysUserEntity user = this.getUser();
        SmsUtil.codeValidate(jedisUtil, user.getMobile(), params.get("code"));
        jedisUtil.set(Constant.VERIFICATION_CARD_SN + user.getUserId(), "1", 3600);
        return RestResponse.success();
    }
    @SysLog("查看用户卡券密钥")
    @PostMapping("getCardSn")
    @RequiresPermissions("mall:usercard:getCardSn")
    public RestResponse getCardSn(@RequestBody Map<String, String> params) {
        String userId = this.getUserId();
        if (!jedisUtil.exists(Constant.VERIFICATION_CARD_SN + userId)) {
            return RestResponse.success().put("verificationCardSn", "0");
        }
        return RestResponse.success()
                .put("verificationCardSn", "1")
                .put("cardSn", mallUserCardService.getById(params.get("id")).getCardSn());
    }

    /**
     * 新增用户卡卷
     *
     * @param mallUserCard mallUserCard
     * @return RestResponse
     */
    @SysLog("新增用户卡卷")
    @RequestMapping("/save")
    @RequiresPermissions("mall:usercard:save")
    public RestResponse save(@RequestBody MallUserCardEntity mallUserCard) {

        mallUserCardService.add(mallUserCard);

        return RestResponse.success();
    }

    /**
     * 修改用户卡卷
     *
     * @param mallUserCard mallUserCard
     * @return RestResponse
     */
    @SysLog("修改用户卡卷")
    @RequestMapping("/update")
    @RequiresPermissions("mall:usercard:update")
    public RestResponse update(@RequestBody MallUserCardEntity mallUserCard) {

        mallUserCardService.update(mallUserCard);

        return RestResponse.success();
    }

    /**
     * 根据主键删除用户卡卷
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除用户卡卷")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:usercard:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        mallUserCardService.deleteBatch(ids);

        return RestResponse.success();
    }
}
